import { message } from 'ant-design-vue'
import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import CryptoJS from 'crypto-js'
// import { CRY_KEY } from '@common/constants'
import { useUserStore } from '../stores/user'

const key = CryptoJS.enc.Utf8.parse('duodiantong19958888..00...+--+--')
// import { useUserStore } from '@renderer/store'
// import { ElMessage } from 'element-plus';
// import { env } from 'process';

let baseHttp = ''

// if (process.env.NODE_ENV === 'production') {
//   baseHttp = 'https://api.duodiantong.cn'
// } else {
//   baseHttp = 'http://127.0.0.1:7001'
// }

const request = axios.create({
  baseURL: baseHttp, //location.origin || baseHttp,
  timeout: 1000 * 60
})

request.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  // const userStore = useUserStore()
  config.headers['Authorization'] = `Bearer ${localStorage.getItem('token')}`
  return config
})

request.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.data.code === 422) {
      const errorData = response.data.detail
        .map((item) => `${item.field}: ${item.message}`)
        .join(', ')
      message.error(errorData || '请求参数错误')
      return Promise.reject(response.data)
    }
    if (response.data.code === 302) {
      message.error(response.data.error || '请求失败')
      return Promise.reject(response.data)
    }
    if (response.data.code === 303) {
      // message.error(response.data.error || '请求失败')
      // 调用退出登陆
      const userStore = useUserStore()
      userStore.logout()
      return Promise.reject(response.data)
    }
    try {
      if (response.data.code === 0 && response.data.data) {
        // 解析数据
        const decrypted = CryptoJS.AES.decrypt(response.data.data, key, {
          mode: CryptoJS.mode.ECB,
          padding: CryptoJS.pad.Pkcs7
        }).toString(CryptoJS.enc.Utf8)
        if (!decrypted) {
          return Promise.resolve(response.data)
        }
        response.data.data = JSON.parse(decrypted)
        return Promise.resolve(response.data)
      }
    } catch (e) {
      message.error('数据有误,请联系管理员')
      return Promise.reject(e)
    }

    return Promise.resolve(response.data)
  },
  (error: AxiosError) => {
    let message = error.message
    console.log(error)
    if (message === 'Network Error') {
      message = '后端网络故障'
      // ElMessage.error(message);
    } else if (message.includes('timeout')) {
      message = '接口请求超时'
      // ElMessage.error(message);
    } else if (message.includes('Request failed with status code')) {
      // if (message.substring(message.length - 3) == 500) {
      //   axios({
      //     url: `${error.config.baseURL}${error.config.url}`,
      //     method: error.config.method,
      //     headers: error.config.headers,
      //     data: error.config.data
      //   }).catch((err) => {
      //     message = `接口${message.substring(message.length - 3)}异常`
      //     // ElMessage.error(message);
      //   })
      // }
    }

    return Promise.reject(error)
  }
)

export default request
